import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_2b_client/apis/MarketDeliveryOrderApi.dart';
import 'package:flutter_2b_client/store/EmployeeAuthorizationStore.dart';
import 'package:flutter_2b_client/utils/MobxHooks.dart';
import 'package:flutter_2b_client/utils/Page.dart';
import 'package:flutter_2b_client/utils/PagingUtils.dart';
import 'package:flutter_2b_client/utils/local_datetime.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:provider/provider.dart';

import '../components/GoodsListItem.dart';
import '../components/LoadingButton.dart';
import '../components/showConfirmDialog.dart';
import '../theme/custom_color.dart';
import 'package:dio/dio.dart';

class MarketDeliveryOrderDetailPage extends HookWidget {
  final int orderId;

  const MarketDeliveryOrderDetailPage(this.orderId, {Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var scrollController = useScrollController();
    var marketDeliveryOrderDetailState =
        useState<MarketDeliveryOrderDetail?>(null);
    useEffect(() {
      marketDeliveryOrderApi
          .getMarketDeliveryOrderDetail(orderId)
          .then((value) => marketDeliveryOrderDetailState.value = value);
      return null;
    }, [orderId]);

    var pagingController =
        usePagingController<Pageable, OrderItemInOrderSummary>(
            firstPageKey: Pageable());
    var totalElementsState = useState(0);
    usePagingControllerListener(
        pagingController,
        (pageable) => marketDeliveryOrderApi
                .queryOrderItemsInOrder(orderId, pageable.toRequestParamsMap())
                .then((value) {
              totalElementsState.value = value.totalElements;
              return value;
            }),
        (item) => item.goodsId,
        [orderId]);
    final me = useObservable(() => Provider.of<EmployeeAuthorizationStore>(context).me);

    var showValidateButton =
        marketDeliveryOrderDetailState.value?.validatedDateTime == null &&
            me?.hasAuthority("卖场_送货单_验收") == true;

    var showAddButton = showValidateButton;
    scrollToLast(){
      scrollController.animateTo((pagingController.itemList?.length??0) * 80, duration: const Duration(milliseconds: 300), curve: Curves.ease);
    }

    return Scaffold(
      bottomNavigationBar: showAddButton || showValidateButton
          ? BottomAppBar(
              child: Row(
                children: [
                  if (showValidateButton)
                    LoadingButton(
                      onPressed: () async {
                        await marketDeliveryOrderApi
                            .validateMarketDeliveryOrder(orderId);
                        marketDeliveryOrderDetailState.value =
                            marketDeliveryOrderDetailState.value?.copyWith(
                                validatedDateTime: LocalDateTime.now());
                      },
                      child: const Text("验收"),
                    ),
                  if (showAddButton)
                    IconButton(
                        onPressed: () async {
                          var goodsId = await context.push(Uri(
                              path: "/goods",
                              queryParameters: {
                                "editMarketDeliveryOrderId": orderId.toString()
                              }).toString()) as int?;
                          if (goodsId != null) {
                            var orderItemInOrderSummary =
                                await marketDeliveryOrderApi.addItemFromGoodsId(
                                    orderId, goodsId);
                            pagingController.itemList =
                                pagingController.itemList?.toList()
                                  ?..add(orderItemInOrderSummary);
                            Fluttertoast.showToast(
                              msg: "添加成功！${orderItemInOrderSummary.name}",
                            );
                            scrollToLast();
                          }
                        },
                        icon: const Icon(Icons.add)),
                ],
              ),
            )
          : null,
      floatingActionButton: showAddButton
          ? FloatingActionButton(
              onPressed: () async {
                var barcode = (await context.push(
                  Uri(
                    path: "/scanBarcode",
                    queryParameters: {
                      "marketDeliveryOrderId": orderId.toString(),
                    },
                  ).toString(),
                )) as String?;
                if (barcode != null) {
                  var response = await marketDeliveryOrderApi
                      .addItemFromBarcode(orderId, barcode);
                  var list = pagingController.itemList?.toList();
                  list?.add(response);
                  pagingController.itemList = list;
                  totalElementsState.value += 1;

                  Fluttertoast.showToast(
                    msg: "扫描成功！${response.name} ",
                  );
                  scrollToLast();
                }
              },
              child: const Icon(Icons.document_scanner),
            )
          : null,
      body: CustomScrollView(
        controller: scrollController,
        slivers: [
          SliverAppBar(
            expandedHeight: 200,
            pinned: true,
            title: const Text("订单详情"),
            actions: const [],
            flexibleSpace: FlexibleSpaceBar(
              background: Padding(
                padding: const EdgeInsets.only(left: 16),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "卖场：${marketDeliveryOrderDetailState.value?.market.name ?? ""}",
                    ),
                    Text(
                      "开单时间：${marketDeliveryOrderDetailState.value?.createdDateTime.format() ?? ""}",
                    ),
                    if (marketDeliveryOrderDetailState
                            .value?.validatedDateTime !=
                        null)
                      Text(
                        "验收时间：${marketDeliveryOrderDetailState.value?.validatedDateTime?.format() ?? ""}",
                      ),
                    Text(
                      "${totalElementsState.value}个单品",
                    ),
                    TextButton(
                        onPressed: () {
                          context.push(
                              "/markets/${marketDeliveryOrderDetailState.value?.market.id}/orders/$orderId");
                        },
                        child: const Text("查看原订单")),
                  ],
                ),
              ),
            ),
          ),
          PagedSliverList(
            pagingController: pagingController,
            builderDelegate: PagedChildBuilderDelegate<OrderItemInOrderSummary>(
                itemBuilder: (BuildContext context,
                    OrderItemInOrderSummary item, int index) {
              return GestureDetector(
                onLongPress: () {
                  showConfirmDeleteGoodsDialog(
                     context,
                    barcode: item.barcode,
                    name: item.name,
                    onConfirm: () async {
                      await marketDeliveryOrderApi.deleteOrderItem(
                          orderId, item.goodsId);
                      var newItemList = pagingController.itemList
                          ?.where((element) =>
                      element.goodsId != item.goodsId)
                          .toList();

                      if (pagingController.nextPageKey != null &&
                          pagingController.itemList != null) {
                        var queryPage = await marketDeliveryOrderApi
                            .queryOrderItemsInOrder(
                            orderId,
                            Pageable(
                                page: pagingController
                                    .itemList!.length,
                                size: 1)
                                .toRequestParamsMap());
                        newItemList?.addAll(queryPage.content);
                      }
                      pagingController.itemList = newItemList;
                      totalElementsState.value -= 1;
                      if(context.mounted){
                        Navigator.pop(context);
                      }

                    }
                  );
                },
                child: MarketDeliveryOrderItem(
                  orderId,
                  item,
                  onUpdateAmount: (amount) {
                    final newList = pagingController.itemList?.toList();
                    var item = newList?[index];
                    if (item != null) {
                      item = item.copyWith(
                          amountInOrder: amount,
                          inStore:
                              item.inStore - (amount - item.amountInOrder));
                      newList?[index] = item;
                      pagingController.itemList = newList;
                    }
                  },
                  edited: showAddButton || showValidateButton,
                ),
              );
            }),
          ),
        ],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endContained,
    );
  }
}

class MarketDeliveryOrderItem extends HookWidget {
  final int orderId;
  final OrderItemInOrderSummary item;
  final Function(int amount) onUpdateAmount;
  final bool edited;

  const MarketDeliveryOrderItem(this.orderId, this.item,
      {Key? key, required this.onUpdateAmount, this.edited = true})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GoodsListItem(
      onUpdateAmount: (int amount,int? unitId) async {
        final adjustedAmount = max(amount, 0);
        return marketDeliveryOrderApi
            .updateOrderItemGoodsAmount(orderId, item.goodsId,
                UpdateItemAmountRequest(amount: adjustedAmount,unitId: unitId))
            .then((value) {
          debugPrint(Theme.of(context)
              .extension<CustomColors>()
              ?.onSuccessContainer
              ?.toString());
          Fluttertoast.showToast(
              msg: "修改商品数量成功",
              backgroundColor:
                  Theme.of(context).extension<CustomColors>()?.successContainer,
              textColor: Theme.of(context)
                  .extension<CustomColors>()
                  ?.onSuccessContainer);
          onUpdateAmount(adjustedAmount);
          return null;
        });
      },
      name: item.name,
      barcode: item.barcode,
      inStore: item.inStore,
      amount: item.amountInOrder,
      boxSpecification: item.boxSpecification,
      edited: edited,
      unit: item.unit,
      units: item.units,
    );
  }
}
